<?php

namespace App\Libs\Views;

class Json extends View
{
    public function show($response) {
        $callback = isset($response['__callback']) ? trim($response['__callback']) : NULL;
        $view = json_encode($this->buildView($response));
        if ( ! empty($callback)) {
            $view = $callback . '(' . $view . ')';
        }
        echo $view;
    }

    public function buildView($response) {
        if (is_array($response)) {
            $code = isset($response['code']) ? intval($response['code']) : 0;
            $message = isset($response['message']) && is_string($response['message']) ? trim($response['message']) : '成功';
            $data = isset($response['data']) ? $response['data'] : NULL;
        } else {
            $code = 0;
            $message = '成功';
            $data = $response;
        }
        return array('code' => $code, 'message' => $message, 'data' => $data);
    }

    public static function view($code = 0, $message = 'ok', $data = NULL) {
	if( !empty($data ) && (is_object($data) || is_array($data) ) ){
	   foreach( $data as $k=>$v ){
		if( is_object($v) ){
			$json = json_decode(json_encode($v),true);
			if( empty($json) ){
				$data[$k] = '';
			}
		}
            }	
	}
        return array('code' => $code, 'message' => $message, 'data' => $data);
    }
}

